import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Login',
    component: LoginView,

  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        component: () => import(/* webpackChunkName: "home" */ '../views/HomeView.vue'),
      },
      {
        path: 'detail',
        name: 'detail',
        component: () => import(/* webpackChunkName: "detail" */ '../views/HomeDetail.vue'),
      },
      {
        path: 'PersonalCenter',
        name: 'PersonalCenter',
        component: () => import(/* webpackChunkName: "PersonalCenter" */ '../views/PersonalCenter.vue'),
      },
    ]

  },
  {
    path: '/Enroll',
    name: 'Enroll',
    component: () => import(/* webpackChunkName: "EnrollViews" */ '../views/EnrollViews.vue')
  },
  {
    path: '*',
    component: () => import(/* webpackChunkName: "*" */ '../views/SiLing.vue'),
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 解决重复点击路由报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err;
  });
};

const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err;
  });
};

// 添加路由守卫
router.beforeEach((to, from, next) => {
  if (to.fullPath === from.fullPath && to.name !== 'Login') {
    return;
  }
// 是否以about开头的路径
  if (to.path.startsWith('/about')) {
    const account = localStorage.getItem('succeed');
    if (account) {
      next();
    } else {
      next('/');
    }
  } else {
    next();
  }
});

export default router;    